//
//  NetWorkRequest.m
//  URLSessionTest
//
//  Created by mac on 2017/7/7.
//  Copyright © 2017年 yyb. All rights reserved.
//

#import "NetWorkRequest.h"
#import "NetWork.h"
#import "NetWorkResponseSerializer.h"


@interface NetWorkRequest ()
@property (nonatomic, strong, readwrite) NSData *responseData;
@property (nonatomic, strong, readwrite) id responseJSONObject;
@property (nonatomic, strong, readwrite) id responseObject;
@property (nonatomic, strong, readwrite) NSString *responseString;
@property (nonatomic, strong, readwrite) NSError *error;
@end

@implementation NetWorkRequest{
    NetWorkJSONResponseSerializer *_jsonResponseSerializer;
    NetWorkXMLParserResponseSerializer *_xmlParserResponseSerialzier;
}
- (NetWorkJSONResponseSerializer *)jsonResponseSerializer {
    if (!_jsonResponseSerializer) {
        _jsonResponseSerializer = [NetWorkJSONResponseSerializer serializer];
        _jsonResponseSerializer.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(100, 500)];
        
    }
    return _jsonResponseSerializer;
}

- (NetWorkXMLParserResponseSerializer *)xmlParserResponseSerialzier {
    if (!_xmlParserResponseSerialzier) {
        _xmlParserResponseSerialzier = [NetWorkXMLParserResponseSerializer serializer];
        _xmlParserResponseSerialzier.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(100, 500)];
    }
    return _xmlParserResponseSerialzier;
}

- (RequestMethod)requestMethod {
    return RequestMethodGET;
}

- (RequestSerializerType)requestSerializerType {
    return RequestSerializerTypeHTTP;
}

- (NSString *)requestUrl {
    return @"";
}

- (NSString *)baseUrl {
    return @"";
}

- (NSString *)cdnUrl {
    return @"";
}

- (BOOL)useCDN {
    return NO;
}

- (NSDictionary *)requestParams {
    return nil;
}

- (NSString *)certificateName {
    return nil;
}

- (ResponseSerializerType)responseSerializerType {
    return ResponseSerializerTypeJSON;
}


- (NSString *)buildReuqestMethod {
    RequestMethod method = [self requestMethod];
    switch (method) {
        case RequestMethodGET:
            return @"GET";
        case RequestMethodPOST:
            return @"POST";
    }
    return @"";
}

- (NSString *)buildRequestURL {
    NSString *detailUrl = [self requestUrl];
    NSURL *temp = [NSURL URLWithString:detailUrl];
    // 如果detail URL有效
    if (temp && temp.host && temp.scheme) {
        return detailUrl;
    }
    NSString *baseUrl;
    if ([self useCDN]) {
        if ([self cdnUrl].length > 0) {
            baseUrl = [self cdnUrl];
        } else {
            baseUrl = [self cdnUrl];
        }
    } else {
        if ([self baseUrl].length > 0) {
            baseUrl = [self baseUrl];
        } else {
            baseUrl = [self baseUrl];
        }
    }
    // URL 比较
    NSURL *url = [NSURL URLWithString:baseUrl];
    if (baseUrl.length > 0 && ![baseUrl hasSuffix:@"/"]) {
        url = [url URLByAppendingPathComponent:@""];
    }
    return [NSURL URLWithString:detailUrl relativeToURL:url].absoluteString;
}

- (void)startWithCompletionBlock:(RequestCompletionBlock)requestCompletionBlock {
    [NetWork requestWithMethod:[self buildReuqestMethod]
                        andURL:[self buildRequestURL]
                     andParams:[self requestParams]
                        andCer:[self certificateName]
          andUseJSONSerializer:[self requestSerializerType] == RequestSerializerTypeJSON
             completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
             self.responseObject = data;
             self.error = error;
             NSError *  serializationError = nil;
             if ([self.responseObject isKindOfClass:[NSData class]]) {
                 self.responseData = data;
                 self.responseString = [[NSString alloc] initWithData:data encoding:[NetWorkRequest stringEncodingWithRequest:response]];
                 switch (self.responseSerializerType) {
                     case ResponseSerializerTypeHTTP:
                         break;
                     case ResponseSerializerTypeJSON:
                     {
                         self.responseObject = [self.jsonResponseSerializer responseObjectForResponse:self.responseObject data:data error:&serializationError];
                         self.responseJSONObject = self.responseObject;
                     }
                         break;
                     case ResponseSerializerTypeXMLParser:
                     {
                         self.responseObject = [self.xmlParserResponseSerialzier responseObjectForResponse:self.responseObject data:data error:&serializationError];
                     }
                         
                         break;
                 }
             }
             
            requestCompletionBlock(self);
    }];
}

+ (NSStringEncoding)stringEncodingWithRequest:(NSURLResponse *)response {
    // From TWAFNetworking 2.6.3
    NSStringEncoding stringEncoding = NSUTF8StringEncoding;
    if (response.textEncodingName) {
        CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
        if (encoding != kCFStringEncodingInvalidId) {
            stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding);
        }
    }
    return stringEncoding;
}
@end
